import 'package:flutter/material.dart';
import 'package:flutter/services.dart';


/// 页面
class Scene00selectfirstthendelete extends StatefulWidget {
  const Scene00selectfirstthendelete({super.key});
  @override
  State<Scene00selectfirstthendelete> createState() => _Scene00selectfirstthendeleteState();
}

class _Scene00selectfirstthendeleteState extends State<Scene00selectfirstthendelete> {
  late MyDeltaInput _input;

  @override
  void initState() {
    super.initState();
    _input = MyDeltaInput(onChanged: () => setState(() {}));
  }

  @override
  void dispose() {
    _input.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('两次删除')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 用 EditableText 展示，并把我们的 client 交给它
            EditableText(
              controller: _input.controller,
              focusNode: FocusNode()..requestFocus(),
              style: const TextStyle(fontSize: 22),
              cursorColor: Colors.blue,
              backgroundCursorColor: Colors.grey,
              selectionColor: Colors.blue.withOpacity(.4),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _input.clear(),
              child: const Text('清空'),
            ),
          ],
        ),
      ),
    );
  }
}

/// 自定义 DeltaTextInputClient
class MyDeltaInput with DeltaTextInputClient {
  MyDeltaInput({required this.onChanged}) {
    _value = const TextEditingValue(text: 'Hello Flutter!');
    _attach();
  }

  late TextInputConnection _conn;
  final VoidCallback onChanged;

  // 对外暴露一个 TextEditingController，让 EditableText 用
  final TextEditingController controller =
  TextEditingController.fromValue(const TextEditingValue(text: 'Hello Flutter!'));

  // 当前内部 value
  late TextEditingValue _value;

  // 上一次删除时留下的“待删除字符”区间
  TextSelection? _pendingDelete;

  void _attach() {
    _conn = TextInput.attach(
      this,
      const TextInputConfiguration(
        inputType: TextInputType.text,
        enableDeltaModel: true, // 必须
      ),
    );
    _conn.show();
  }

  void dispose() {
    _conn.close();
    controller.dispose();
  }

  // 清空
  void clear() {
    _value = const TextEditingValue();
    _pendingDelete = null;
    _apply();
  }

  // 把内部 value 同步给 controller 和 TextInput
  void _apply() {
    controller.value = _value;
    _conn.setEditingState(_value);
    onChanged();
  }

  /* ------------ DeltaTextInputClient 回调 ------------ */

  @override
  TextEditingValue? get currentTextEditingValue => _value;

  @override
  void updateEditingValueWithDeltas(List<TextEditingDelta> deltas) {
    for (final delta in deltas) {
      // 我们只关心 Backspace/Delete 产生的 TextEditingDeltaDeletion
      if (delta is TextEditingDeltaDeletion) {
        _handleDelete(delta);
      } else {
        // 其他输入直接写入
        _value = delta.apply(_value);
        _pendingDelete = null; // 普通输入时取消待删除
      }
    }
    _apply();
  }

  @override
  void connectionClosed() {}

  /* ------------ 删除逻辑 ------------ */

  void _handleDelete(TextEditingDeltaDeletion delta) {
    // 如果当前已经选中 _pendingDelete 区间，则真正删除
    if (_pendingDelete != null &&
        _pendingDelete!.start == delta.deletedRange.start &&
        _pendingDelete!.end == delta.deletedRange.end) {
      _value = delta.apply(_value);
      _pendingDelete = null;
      return;
    }

    // 第一次删除：仅选中该字符
    final int pos = delta.deletedRange.start;
    if (pos < 0 || pos >= _value.text.length) return; // 越界保护

    _pendingDelete = TextSelection(baseOffset: pos, extentOffset: pos+1);
    _value = _value.copyWith(
      selection: _pendingDelete!,
      composing: TextRange.empty,
    );
  }

  @override
  // TODO: implement currentAutofillScope
  AutofillScope? get currentAutofillScope => throw UnimplementedError();

  @override
  void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
    // TODO: implement didChangeInputControl
  }

  @override
  void insertContent(KeyboardInsertedContent content) {
    // TODO: implement insertContent
  }

  @override
  void insertTextPlaceholder(Size size) {
    // TODO: implement insertTextPlaceholder
  }

  @override
  void performAction(TextInputAction action) {
    // TODO: implement performAction
  }

  @override
  void performPrivateCommand(String action, Map<String, dynamic> data) {
    // TODO: implement performPrivateCommand
  }

  @override
  void performSelector(String selectorName) {
    // TODO: implement performSelector
  }

  @override
  void removeTextPlaceholder() {
    // TODO: implement removeTextPlaceholder
  }

  @override
  void showAutocorrectionPromptRect(int start, int end) {
    // TODO: implement showAutocorrectionPromptRect
  }

  @override
  void showToolbar() {
    // TODO: implement showToolbar
  }

  @override
  void updateEditingValue(TextEditingValue value) {
    // TODO: implement updateEditingValue
  }

  @override
  void updateFloatingCursor(RawFloatingCursorPoint point) {
    // TODO: implement updateFloatingCursor
  }
}